<template>
  <admin-container :title="form.id == 0 ? '轮播图添加' : '轮播图编辑'">

    <div class="carousel-form">
      <el-form :model="form" size="small" :rules="rules" ref="carouselForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" maxlength="10" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="Ttile">
          <el-input v-model="form.titleEn" placeholder="Please enter the title" maxlength="100"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入副标题" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="Subhead">
          <el-input v-model="form.subtitleEn" placeholder="Please enter the subtitle" maxlength="255"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" v-model="form.description"
            placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="Description">
          <el-input :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" v-model="form.descriptionEn"
            placeholder="Please enter a description"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="form.subtitleColor"></el-color-picker>
        </el-form-item>
        <el-form-item label="媒体类型" prop="mediaType">
          <div>
            <el-radio-group v-model="form.mediaType">
              <el-radio :label="0">图片</el-radio>
              <el-radio :label="1">视频</el-radio>
            </el-radio-group>
          </div>
          <div v-if="form.mediaType == 0" class="upload-box">
            <div>
              <el-upload :before-upload="upload" accept="image/jpeg,image/jpg" action="#" :limit="1">
                <el-button size="small" type="primary">图片上传</el-button>
                <span class="prompt">* 推荐使用尺寸 1920 * 900, 文件大小不能超过2mb</span>
              </el-upload>
            </div>
            <div class="upload-box-img">
              <img v-if="form.host != '' && form.url != ''" :src="form.host + form.url">
            </div>
          </div>
          <div v-if="form.mediaType == 1" class="upload-box">
            <div>
              <el-upload :before-upload="upload" accept="audio/mp4, video/mp4" action="#" :limit="1">
                <el-button size="small" type="primary">视频上传</el-button>
                <span class="prompt">* 推荐使用尺寸 1920 * 1080, 文件大小不能超过6mb</span>
              </el-upload>
            </div>
            <div class="upload-box-img">
              <video v-if="form.host != '' && form.url != ''" muted autoplay loop :src="form.host + form.url"></video>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button v-if="form.id == 0" type="primary" @click="submit">添加</el-button>
          <el-button v-else type="primary" @click="save">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </admin-container>
</template>

<script>
import AdminContainer from '@/components/Admin/AdminContainer.vue';
import * as carouselApi from '@/api/admin/carouselApi';

export default {
  components: {
    AdminContainer
  },
  data () {
    return {
      form: {
        id: 0,
        title: '',
        subtitle: '',
        subtitleColor: '#806e22',
        description: '',
        host: '',
        url: '',
        mediaType: null,
        titleEn: '',
        subtitleEn: '',
        descriptionEn: ''
      },
      rules: {
        mediaUrl: [
          {
            required: true,
            message: '媒体地址不能为空',
            trigger: 'blur'
          }
        ],
      },
      dialogImageVisible: false,
      reserveUpload: {
        mediaType: null,
        host: '',
        url: '',
      }
    };
  },
  methods: {
    submit () {
      var self = this;
      self.$refs.carouselForm.validate((valid) => {
        if (valid) {
          if (self.form.host == '' || self.form.url == '') {
            self.$message.error('请上传图片或视频');
            return;
          }
          carouselApi.addCarousel(self.form)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: '添加成功',
                  type: 'success'
                });
                self.$router.push({ path: '/management/home/CarouselList' });
              }
              else if (res.code == 500) {
                self.$message.error('添加轮播图接口发生错误');
              }
            })
            .catch(err => {
              self.$message.error('添加轮播图接口发生错误');
            });
        } else {
          return false;
        }
      });
    },
    upload (file) {
      var self = this;
      if (file.type.includes('image/') && file.size > 2 * 1024 * 1024) {
        self.$message.error('上传的图片不能大于2MB');
        return false;
      }
      if (file.type === 'video/mp4' && file.size > 6 * 1024 * 1024) {
        self.$message.error('上传的MP4视频不能大于6MB');
        return false;
      }
      const formData = new FormData();
      formData.append("mediaFile", file);
      carouselApi.uploadMedia(formData)
        .then(res => {
          if (res.code == 200) {
            self.form.host = res.data.host;
            self.form.url = res.data.url;
          }
        })
        .catch(err => {
          self.$message.error('上传发生错误，请重新尝试');
        })
      return false;
    },
    clearUpload (isSwitch) {
      var self = this;
      var reserveObj = null;
      if (self.reserveUpload.mediaType != null && self.form.mediaType == self.reserveUpload.mediaType) {
        //如果切换回了前媒体类型，需要把保留的数据重新赋值
        reserveObj = JSON.parse(JSON.stringify(self.reserveUpload));
        if (isSwitch) {
          //保留
          self.reserveUpload.host = self.form.host;
          self.reserveUpload.url = self.form.url;
          //切换回旧数据
          self.form.host = reserveObj.host;
          self.form.url = reserveObj.url;
        }
      }
    },
    getCarouselById (id) {
      var self = this;
      carouselApi.getCarouselById(id)
        .then(res => {
          if (res.code == 200) {
            self.form = res.data;
          }
          else if (res.code == 500) {
            self.$message.error('编辑对象不存在，请检查参数');
            self.$router.push('/management/home/CarouselList');
          }
        })
        .catch(err => {
          self.$message.error('接口出现错误');
        })
    },
    save () {
      var self = this;
      if (self.form.host == '' || self.form.url == '') {
        self.$message.error('请上传图片或视频');
        return;
      }
      carouselApi.updateCarousel(self.form)
        .then(res => {
          if (res.code == 200) {
            self.$message({
              message: '更新成功',
              type: 'success'
            });
            self.$router.push({ path: '/management/home/CarouselList' });
          }
          else if (res.code == 500) {
            self.$message.error('更新轮播图接口发生错误');
          }
        })
        .catch(err => {
          self.$message.error('更新轮播图接口发生错误');
        });
    }
  },
  watch: {
    'form.mediaType': function (newVal, oldVal) {
      var self = this;
      var isSwitch = self.reserveUpload.mediaType != null;
      self.reserveUpload.mediaType = newVal;
      self.clearUpload(isSwitch);
    }
  },
  mounted () {
    var self = this;
    if (self.$route.query.id != null) {
      self.form.id = parseInt(self.$route.query.id);
      self.getCarouselById(self.form.id);
    }
    else {
      self.form.mediaType = 0;
    }
  }
}
</script>

<style scoped>
.carousel-form {
  padding: 50px 10%;
}

.subtitle-box {
  display: flex;
}

.subtitle-box .subtitle-color {
  width: 50px;
  height: 32px;
  text-align: right;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-box {
  margin-top: 20px;
}

.upload-box-img {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  width: calc(1920px / 5);
  height: calc(900px / 5);
  margin-top: 20px;
  padding: 5px;
}

.upload-box-img img {
  width: 100%;
  height: 100%;
}

.upload-box-img video {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
</style>